package cs276.pe1.lucene;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.spell.Dictionary;
import org.apache.lucene.search.spell.LuceneDictionary;
import org.apache.lucene.search.spell.SpellChecker;
import org.apache.lucene.store.FSDirectory;

import cs276.pe1.spell.SpellingCorrector;

/**
 * Spell checker using the Lucene contributed code.  This extends the SpellingCorrector
 * interface.  This article was very helpful when writing this code: 
 * http://today.java.net/lpt/a/211
 * @author alecmgo@gmail.com
 */
public class LuceneSpellChecker implements SpellingCorrector {
  private final SpellChecker spellChecker;
  private static final String RANDOM_WORD = "washington";

  /**
   * Constructor.  If the index doesn't exist, build it.  Currently, this is implemented by
   * checking if a random word exists in the index.  
   * @throws IOException
   */
  public LuceneSpellChecker() throws IOException {
    IndexReader indexReader = IndexReader.open(System.getProperty("user.home") + "/cs276-index");
    this.spellChecker = new SpellChecker(FSDirectory.getDirectory(System.getProperty("user.home") + "/cs276-spell-index"));

    if(!spellChecker.exist(RANDOM_WORD)) {
      //TODO: Make this more robust.  This is a temporary hack.
      Dictionary dictionary = new LuceneDictionary(indexReader, "plots");
      spellChecker.indexDictionary(dictionary);
    }
  }

  /**
   * Returns a list of top corrections.
   */
  public List<String> corrections(String word) {
    List<String> c = new ArrayList<String>();
    try {
      for(String s : spellChecker.suggestSimilar(word, 10)) {
        c.add(s);
      }
    } catch(Exception e) {
      System.out.println("Exception");
    }
    return c;    
  }
}
